package com.bestcem.xm.om.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.bestcem.xm.common.core.domain.web.ServiceResult;
import com.bestcem.xm.common.core.enums.ResourceErrorCodeEnum;
import com.bestcem.xm.om.dao.PackMiddleDao;
import com.bestcem.xm.om.dao.PlatformDao;
import com.bestcem.xm.om.entity.OmPlatform;
import com.bestcem.xm.om.grpc.service.param.OmPlatformParam;
import com.bestcem.xm.om.service.PlatformService;
import com.bestcem.xm.om.service.dto.PlatformDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 合作伙伴业务层
 *
 * @author zhangfeng <feng.zhang@idiaoyan.com>
 * @version v1.0
 * @date 2022/3/22 10:42
 */
@Slf4j
@Service
public class PlatformServiceImpl implements PlatformService {
    @Resource
    private PlatformDao platformDao;
    @Resource
    private PackMiddleDao packMiddleDao;

    @Override
    public ServiceResult<PlatformDTO> findOneByCode(String code) {
        OmPlatform omPlatform = platformDao.findOneByPlatformCode(code);
        PlatformDTO platformDTO = BeanUtil.copyProperties(omPlatform, PlatformDTO.class);
        return ServiceResult.success(platformDTO);
    }

    @Override
    public ServiceResult<List<PlatformDTO>> listPlatforms(OmPlatformParam param) {
        List<OmPlatform> platformList = platformDao.listByPlatformParam(param);
        List<PlatformDTO> platformDTOList = platformList.stream()
                .map(o -> BeanUtil.copyProperties(o, PlatformDTO.class)).collect(Collectors.toList());
        return ServiceResult.success(platformDTOList);
    }

    @Override
    public ServiceResult<PlatformDTO> getPlatformByOrgId(String orgId) {
        OmPlatform platform = platformDao.findOneByOrgId(orgId);
        if (Objects.isNull(platform)) {
            return ServiceResult.fail(ResourceErrorCodeEnum.NOT_FOUND, "合作伙伴信息不存在");
        }
        List<String> packIdList = packMiddleDao.listPackIdsByPlatformId(platform.getId());
        PlatformDTO platformDTO = BeanUtil.copyProperties(platform, PlatformDTO.class);
        platformDTO.setPackIdList(packIdList);
        platformDTO.setCreateTime(null);
        return ServiceResult.success(platformDTO);
    }
}
